<template>
  <div class="first-step-container">
    <div class="form-title">{{ formTitle }}</div>
    <form-builder
      ref="form"
      :fields="formFields"
      :value="formValue"
      @update="update"
    >
      <!-- start 计划时间 -->
      <template slot="planTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName" :validation="validation.planTime">
          <form-plantime :picker-options="action == 'create' ? planTimeDatePickerOptions : {}" :field="field" :value="value" @update="update"></form-plantime>
        </form-item>
      </template>
      <!-- end 计划时间 -->
      <!-- start 计划开始时间 -->
      <template slot="planStartTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-planstarttime
            :picker-options="planTimeDatePickerOptions"
            :field="field"
            :value="value"
            @update="update"
            @planTimeChange="planTimeChange"
          ></form-planstarttime>
        </form-item>
      </template>
      <!-- end 计划开始时间 -->

      <!-- start 计划完成时间 -->
      <template slot="planEndTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-planendtime
            :picker-options="planTimeDatePickerOptions"
            :field="field"
            :value="value"
            @update="update"
            @planTimeChange="planTimeChange"
          ></form-planendtime>
        </form-item>
      </template>
      <!-- end 计划完成时间 -->
      <!-- start 活动名称 -->
      <template slot="activitiesName" slot-scope="{ field, value }">
        <form-item :label="field.displayName" :validation="validation.activitiesName">
          <form-text :field="field" :value="value" @update="update"></form-text>
        </form-item>
      </template>
      <!-- start 活动开始时间 -->
      <template slot="activitiesStartTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-date
            :field="field"
            :value="value"
            :disabled-date="time => pickerActiveTimeOptions(time, formValue.activitiesEndTime)"
            @input="value => update({field, newValue: value})"
          ></form-date>
        </form-item>
      </template>
      <!-- end 活动开始时间 -->
      <!-- start 活动结束时间 -->
      <template slot="activitiesEndTime" slot-scope="{ field, value }">
        <form-item :label="field.displayName">
          <form-date
            :field="field"
            :value="value"
            :disabled-date="time => pickerActiveTimeOptions(formValue.activitiesStartTime, time)"
            @input="value => update({field, newValue: value})"
          ></form-date>
          <div class="tips">{{$t('smartPlan.activityTip1')}}</div>
        </form-item>
      </template>
      <!-- end 活动结束时间 -->
    </form-builder>
    <!-- 工单、事件派单设置 -->
    <div class="plan-allot-container" v-if="showAllotInfo">
      <div class="allot-title">{{ allotTitle }}</div>
      <task-allot-select
        v-if="bizType == 'TASK'"
        :task-config="taskConfig"
        @update:type="changeAllotType"
        @update:synergies="changeSynergies"
        @update:executors="changeExecutors"
        :edit-value="editAllotSetting"
      ></task-allot-select>
      <event-assign-info
        ref="eventAssignInfo"
        v-if="bizType == 'EVENT'"
        :event-config="eventConfig"
        :edit-value="editAllotSetting"
      ></event-assign-info>
    </div>
  </div>
</template>

<script>
/* components */
import TaskAllotSelect from './taskAllotSelect'
import EventAssignInfo from './eventAssignInfo'
/* constant */
import { 
  PLAN_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
  PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
  PLAN_END_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
} from '@src/model/const/Alert.ts'
/* utils */
import { isOpenData } from '@src/util/platform'
import { packSaveForm } from '../../util/index'
import { safeNewDate } from '@src/util/time';
import { getTimestamp, parseDateTime, useFormTimezone, isEmpty } from 'pub-bbx-utils'
import { t } from '@src/locales'
const { disposeFormSubmitTime } = useFormTimezone()


export default {
  name: 'first-step',
  props: {
    bizType: {
      type: [String, Number],
      default: 'TASK'
    },
    editValue: {
      type: Object,
      default: () => ({})
    },
    editAllotSetting: {
      type: Object,
      default: () => ({})
    },
    fields: {
      type: Array,
      default: () => []
    },
    taskConfig: {
      type: Object,
      default: () => ({})
    },
    eventConfig: {
      type: Object,
      default: () => ({})
    },
    action: {
      type: String,
      default: 'create'
    },
  },
  data() {
    return {
      formValue: {},
      allotSetting: {
        allotType: 'normal',
        executors: [],
        synergies: [],
      },
      planTimeDatePickerOptions: {
        disabledDate(time) {
          return time.getTime() < safeNewDate(safeNewDate().toLocaleDateString()).getTime()
        }
      },
      validation: this.buildValidation(),
    }
  },
  computed: {
    formFields() {
      // 不显示客户、联系人、客户地址、产品字段
      return this.fields.filter(f => !['customer', 'linkman', 'customerAddress', 'product'].includes(f.formType))
    },
    showAllotInfo() {
      return ['TASK', 'EVENT'].includes(this.bizType)
    },
    formTitle() {
      if (this.bizType == 'TASK') {
        return t('smartPlan.formTitle[0]')
      } else if (this.bizType == 'EVENT') {
        return t('smartPlan.formTitle[1]')
      } else if (this.bizType == 'PAAS') {
        return t('smartPlan.formTitle[2]')
      }
      return t('smartPlan.formTitle[0]')
    },
    allotTitle() {
      if (this.bizType == 'TASK') {
        return t('smartPlan.taskAllotTitle')
      }
      return t('smartPlan.eventAssignTitle')
    },
  },
  watch: {
    editValue: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.formValue = newValue
      }
    },
    editAllotSetting: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (!isEmpty(newValue)) {
          this.allotSetting = newValue
        }
      }
    },
  },
  methods: {
    update({ field, newValue, oldValue }) {
      let { fieldName } = field;
      let value = this.formValue;
      this.$set(value, fieldName, newValue);
      this.$emit('input', value);
    },
    planTimeChange({ field, newValue, oldValue }) {
      let { fieldName, formType } = field;
      let nowTime = safeNewDate().getTime();
      let tip = formType == 'planStartTime' ? PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE : PLAN_END_TIME_NOT_LESS_THEN_NOW_MEESSAGE
      if(newValue && newValue < nowTime) {
        return this.$platform.notification({
          title: tip,
          type: 'error'
        })
      }
      
      if(this.formValue.planEndTime && this.formValue.planStartTime) {
        let sTime = this.formValue.planStartTime;
        let eTime = this.formValue.planEndTime;
        if((sTime >= eTime)){
          return this.$platform.notification({
            title: t('task.tip.planTimeTip6'),
            type: 'error'
          })
        }
      }
      if(fieldName === 'planEndTime') {
        if(newValue && newValue < this.formValue.planStartTime) {
          return this.$platform.notification({
            title: t('task.tip.planTimeTip7'),
            type: 'error'
          })
        }
      }
    },
    pickerActiveTimeOptions(startTime, endTime) {
      let end = getTimestamp(endTime)
      let start = getTimestamp(startTime)
      if (!end || !start) return false
      return end < start
    },
    buildValidation() {
      return Object.freeze({
        planTime(value, field, changeStatus){
          changeStatus(true);
          
          let isDateTimeType = field?.setting?.dateType == 'dateTime';
          let errorMessage = '';
          
          if(isDateTimeType) {
            let planTime = parseDateTime(value).getTime();
            let nowTime = safeNewDate().getTime();
            errorMessage = planTime < nowTime && this.action == 'create' ? PLAN_TIME_NOT_LESS_THEN_NOW_MEESSAGE : '';
          }
          
          return new Promise((resolve, reject) => {
            changeStatus(false);
            resolve(errorMessage)
          })
        },
        activitiesName(value, field, changeStatus){
          changeStatus(true);
          let errorMessage = '';
          
          if(value.length > 50) {
            errorMessage = t('common.validate.maxLen', {limit: 50})
          }
          
          return new Promise((resolve, reject) => {
            changeStatus(false);
            resolve(errorMessage)
          })
        },
      })
    },
    /* 更改派单类型 */
    changeAllotType(value) {
      this.allotSetting.allotType = value;
    },
    /* 更改协同人 */
    changeSynergies(value) {
      this.allotSetting.synergies = value;
    },
    /* 更改协同人 */
    changeExecutors(value) {
      this.allotSetting.executors = value;
    },
    buildParams() {
      const params = {}
      let formValue = disposeFormSubmitTime(this.fields, this.formValue) // 处理国际化时间转换
      params.planBasicData = packSaveForm(this.fields, formValue)
      if (this.bizType == 'TASK') {
        params.allotSetting = this.allotSetting
      } else if (this.bizType == 'EVENT') {
        const eventAssignInfo = this.$refs.eventAssignInfo
        params.allotSetting = {
          eventAssignIsAuto: eventAssignInfo.eventAssignIsAuto,
          executorId: eventAssignInfo.executorId,
          executorName: eventAssignInfo.executorName,
          synergies: eventAssignInfo.synergies,
        }
      }
      return params
    },
    async validate() {
      const valid = await this.$refs.form.validate()
      if (!valid) return false
      if(this.formValue.planStartTime && this.formValue.planEndTime){
        let startTime = this.formValue.planStartTime
        let endTime = this.formValue.planEndTime
        if(startTime >= endTime){
          this.$platform.notification({
            title: t('task.tip.planTimeTip6'),
            type: 'error'
          })
          return false
        }
      }
      let nowTime = safeNewDate().getTime();
      if (this.formValue.planStartTime) {
        if (this.formValue.planStartTime < nowTime) {
          this.$platform.notification({
            title: PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
            type: 'error'
          })
          return false
        }
      }
      if (this.formValue.planEndTime) {
        if (this.formValue.planEndTime < nowTime) {
          this.$platform.notification({
            title: PLAN_END_TIME_NOT_LESS_THEN_NOW_MEESSAGE,
            type: 'error'
          })
          return false
        }
      }
      if (this.bizType == 'TASK' && this.allotSetting?.allotType == 'normal' && !this.allotSetting?.executors?.length) {
        this.$platform.notification({
          title: t('task.tip.editTip7'),
          type: 'error'
        })
        return false
      }
      if (this.bizType == 'EVENT' && this.$refs.eventAssignInfo) {
        const eventAssignIsAuto = this.$refs.eventAssignInfo.eventAssignIsAuto
        const executorId = this.$refs.eventAssignInfo.executorId
        if (!eventAssignIsAuto && !executorId) {
          this.$platform.notification({
            title: t('smartPlan.selectEventExecutor'),
            type: 'error'
          })
          return false
        }
      }
      
      return true
    },
  },
  components: {
    [TaskAllotSelect.name]: TaskAllotSelect,
    [EventAssignInfo.name]: EventAssignInfo,
  }
}
</script>

<style lang="scss" scoped>
.first-step-container {
  .form-title, .allot-title {
    width: 100%;
    height: 38px;
    display: flex;
    align-items: center;
    padding: 8px 12px;
    border-radius: 4px;
    font-weight: 500;
    background: #F7F8F8;
  }
  .tips {
    font-size: 12px;
    color: #8c8c8c;
    margin-top: 4px;
    height: 20px;
    line-height: 20px;
  }
}
</style>